package com.study.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Solution_93 {
    List<String> res = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {

        restore(s, 0, "");
        return res;
    }

    public void restore(String s, int index, String ipTry) {
        int sLen = s.length();
        int dotCount = dotCount(ipTry);
        if (dotCount == 3) {
            if (index == sLen) {
                res.add(ipTry);
            } else {
                return;
            }
        } else if (dotCount > 3) {
            return;
        }

        int idx = index + 1;
        for (int i = 0; i < 4 && idx < sLen; i++) {


            String sub = s.substring(index, idx);
            if ("".equals(sub)) {
                continue;
            }
            if (sub.startsWith("0")) {
                return;
            }
            if (Integer.parseInt(sub) > 255) {
                return;
            }
            String s1 = "".equals(ipTry) ? sub
                    : ipTry + "." + sub;
            restore(s, idx, s1);

            idx = i + index + 1;
        }
    }

    private int dotCount(String ipTry) {
        int count = 0;
        for (int i = 0; i < ipTry.length(); i++) {
            if (ipTry.charAt(i) == '.') {
                count++;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        Solution_93 solution93 = new Solution_93();
        List<String> strings = solution93.restoreIpAddresses("25525511135");
        System.out.println("strings = " + strings);
    }
}
